package com.buobao.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.buobao.entity.Book;
import com.buobao.entity.Member;
import com.buobao.entity.MemberReadState;
import com.buobao.service.BookService;
import com.buobao.service.CategoryService;
import com.buobao.service.MemberReadStateService;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
public class BookController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private BookService bookService;
    @Resource
    private MemberReadStateService memberReadStateService;

    @GetMapping("/")
    public ModelAndView showIndex(){
        ModelAndView modelAndView = new ModelAndView("/index");
        modelAndView.addObject("categoryList", categoryService.selectAll());
        return modelAndView;
    }

    @GetMapping("/booklist")
    @ResponseBody
    public IPage<Book> getBookList(Long categoryId,String order,Integer pageIndex){
        IPage<Book> paging = bookService.paging(categoryId,order,pageIndex, 10);
        return paging;
    }

    /**
     * 转发封面地址以解决跨域加载图片的问题，这里直接加载跨域图片无法显示，主要是图片所在服务不支持跨域，当前项目无法配置
     * @param imgUri
     * @return
     */
    @GetMapping("/bookcover")
    public ResponseEntity<byte[]> getBookCover(String imgUri) {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG));
        headers.set("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/125.0.0.0");
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(imgUri, HttpMethod.GET, entity, byte[].class);
        return response;
    }

    private String regex = "https?://[-a-zA-Z0-9+&@#/%?=~_|!:.,;]*[-a-zA-Z0-9+&@#/%=~_|]";
    private Pattern pattern = Pattern.compile(regex);

    @GetMapping("/book/{id}")
    public ModelAndView getBookDetail(@PathVariable("id") Long bookId){
        ModelAndView modelAndView = new ModelAndView("/detail");
        Book book = bookService.selectBookById(bookId);
        modelAndView.addObject("book",book);
        String description = book.getDescription();
        Matcher matcher = pattern.matcher(description);
        while (matcher.find()) {
            String imgUri = matcher.group();
            description = description.replace(imgUri, "/bookcover?imgUri="+imgUri);
        }
        book.setDescription(description);

        return modelAndView;
    }

    @GetMapping("/book/readstate")
    @ResponseBody
    public Map getBookReadState(Long memberId,Long bookId, HttpServletRequest request){
        HttpSession session = request.getSession();
        Member member = (Member) session.getAttribute("member");
        Map<String,Object> result = new HashMap<>();
        if (member!=null) {
            MemberReadState memberReadState = memberReadStateService.selectByMemberIdAndBookId(member.getMemberId(), bookId);
            if (memberReadState!=null) {
                result.put("readState", memberReadState.getReadState());
            } else {
                result.put("readState", 0);
            }
        }
        return result;
    }


    @PostMapping("/book/updatestate")
    @ResponseBody
    public Map updateReadState(Long memberId,Long bookId,Integer readState){
        Map result = new HashMap<String,Object>();
        if (readState==0) {
            memberReadStateService.delete(memberId, bookId);
        } else {
            MemberReadState memberReadState = new MemberReadState();
            memberReadState.setMemberId(memberId);
            memberReadState.setReadState(readState);
            memberReadState.setCreateTime(new Date());
            memberReadState.setBookId(bookId);
            memberReadStateService.insert(memberReadState);
        }
        result.put("readState",readState);
        return result;
    }
}









